package com.liuliang.service.impl;

import com.liuliang.entity.Student;
import com.liuliang.repository.StudentRepository;
import com.liuliang.service.StudentService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 业务逻辑层：StudentServiceImpl实现类
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentRepository studentRepository;

    //查询所有
    @Override
    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    //通过id查询
    @Override
    public Student findById(Integer id) {
        return studentRepository.findById(id).orElse(null);
    }

    //新增和修改
    @Override
    public void save(Student student) {
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        student.setCreateTime(now);
        studentRepository.save(student);
    }

    //删除
    @Override
    public void delete(Integer id) {
        studentRepository.deleteById(id);
    }

    //批量删除
    @Override
    public void batchDelete(List<Integer> ids) {
        studentRepository.deleteAllById(ids);
    }

    //分页条件查询
    @Override
    public Page<Student> findByPage(Integer pageNum, Integer pageSize, String name, String birthplace, String major) {
        //构建分页查询条件
        Sort sort = Sort.by(Sort.Direction.ASC, "id"); //根据id进行降序排序
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, sort);
        return studentRepository.findByLike(name, birthplace, major, pageRequest);
    }
}